package com.anyou.mall.goo.goods.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.anyou.common.core.domain.ApiResult;
import com.anyou.mall.goo.goods.domain.GooGoods;
import com.anyou.mall.goo.goods.domain.JfDraw;
import com.anyou.mall.goo.goods.dto.*;
import com.anyou.mall.goo.goods.mapper.GooGoodsMapper;
import com.anyou.mall.goo.goods.mapper.JfDrawMapper;
import com.anyou.mall.goo.goods.service.IGooGoodsService;
import com.anyou.mall.goo.goods.service.IJfDrawService;
import com.anyou.mall.goo.goodsSku.domain.GooGoodsSku;
import com.anyou.mall.goo.goodsSku.mapper.GooGoodsSkuMapper;
import com.anyou.mall.goo.goodsSpecs.domain.GooGoodsSpecs;
import com.anyou.mall.goo.goodsSpecs.domain.GooGoodsSpecsValue;
import com.anyou.mall.goo.goodsSpecs.mapper.GooGoodsSpecsMapper;
import com.anyou.mall.goo.goodsSpecs.mapper.GooGoodsSpecsValueMapper;
import com.anyou.mall.goo.parameter.domain.GooGoodsParameter;
import com.anyou.mall.goo.parameter.domain.GooGoodsParameterValue;
import com.anyou.mall.goo.parameter.mapper.GooGoodsParameterMapper;
import com.anyou.mall.goo.parameter.mapper.GooGoodsParameterValueMapper;
import com.anyou.mall.goo.specs.domain.SpeSpecs;
import com.anyou.mall.help.domain.HelpDocument;
import com.anyou.mall.help.mapper.HelpDocumentMapper;
import com.anyou.mall.parts.mapper.PlaPartsClassifyMapper;
import com.anyou.mall.sho.domain.CarPartsShop;
import com.anyou.mall.sho.mapper.CarPartsShopAuditMapper;
import com.anyou.mall.sho.mapper.CarPartsShopMapper;
import com.anyou.mall.sho.mapper.ShopNoticeMapper;
import com.anyou.mall.use.mapper.UserNoticeMapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;

/**
 * 商品Service业务层处理
 *
 * @author ruoyi
 * @date 2022-03-24
 */
@Service
public class GooGoodsServiceImpl extends ServiceImpl<GooGoodsMapper, GooGoods> implements IGooGoodsService
{
    @Autowired
    private GooGoodsMapper gooGoodsMapper;

    @Autowired
    private PlaPartsClassifyMapper plaPartsClassifyMapper;


    @Autowired
    private GooGoodsParameterMapper goodsParameterMapper;

    @Autowired
    private GooGoodsParameterValueMapper goodsParameterValueMapper;

    @Autowired
    private GooGoodsSpecsMapper goodsSpecsMapper;

    @Autowired
    private GooGoodsSpecsValueMapper goodsSpecsValueMapper;

    @Autowired
    private GooGoodsSkuMapper goodsSkuMapper;

    @Autowired
    private CarPartsShopMapper carPartsShopMapper;


    @Autowired
    private ShopNoticeMapper shopNoticeMapper;

    @Autowired
    private CarPartsShopAuditMapper carPartsShopAuditMapper;

    @Autowired
    private UserNoticeMapper userNoticeMapper;

    @Autowired
    private HelpDocumentMapper helpDocumentMapper;

    @Autowired
    private JfDrawMapper jfDrawMapper;

    @Autowired
    private IJfDrawService jfDrawService;

    /**
     * 查询商品
     *
     * @param goodsId 商品主键
     * @return 商品
     */
    @Override
    public ApiResult<GooGoods> selectGooGoodsByGoodsId(Long goodsId)
    {
        /*GooGoods goods = gooGoodsMapper.selectGooGoodsByGoodsId(goodsId);
        if(goods == null){
            return ApiResult.error("商品编号错误或不存在");
        }
        //分类名称处理
        if(StringUtils.isNotBlank(goods.getPartsClassifyId())){
            List<Integer> idList = new ArrayList<>();
            List<String> stringList = Arrays.asList(goods.getPartsClassifyId().split(","));
            stringList.forEach(id -> idList.add(Integer.parseInt(id)));
            List<PlaPartsClassify> plaPartsClassifyList = plaPartsClassifyMapper.selectList(new LambdaQueryWrapper<PlaPartsClassify>().in(PlaPartsClassify::getPartsClassifyId, idList));
            goods.setPartsClassifyName(plaPartsClassifyList.stream().map(PlaPartsClassify::getPartsClassifyName).collect(Collectors.joining(",")));
        }




        //参数list
        List<GooGoodsParameter> parameterList = getParameterList(goodsId);
        goods.setParameterList(parameterList);

        //规格list
        List<SpeSpecs> specsList = goodsSpecsMapper.getListByGoodsId(goodsId);
        if(!specsList.isEmpty()){
            specsList.forEach(e -> {
                List<SpeSpecsValue> specsValueList = goodsSpecsValueMapper.getListByGoodsSpecsId(e.getGoodsSpecsId());
                e.setSpecsValueList(specsValueList);
            });
            goods.setSpecsList(specsList);
        }

        //sku list
        List<GooGoodsSku> skuList = goodsSkuMapper.selectList(new LambdaQueryWrapper<GooGoodsSku>().eq(GooGoodsSku::getGoodsId, goodsId));
        goods.setSkuList(skuList);*/
        return ApiResult.success(new GooGoods());
    }

    private List<GooGoodsParameter> getParameterList(Long goodsId) {
        List<GooGoodsParameter> list = goodsParameterMapper.selectList(new LambdaQueryWrapper<GooGoodsParameter>().eq(GooGoodsParameter::getGoodsId, goodsId));
        if(!list.isEmpty()){
            list.forEach(e ->{
                List<GooGoodsParameterValue> valueList = goodsParameterValueMapper.selectList(new LambdaQueryWrapper<GooGoodsParameterValue>().eq(GooGoodsParameterValue::getGoodsParameterId, e.getGoodsParameterId()));
                e.setParameterValueList(valueList);
            });
        }
        return list;
    }



    /**
     * 查询商品列表
     *
     * @param gooGoods 商品
     * @return 商品
     */
    @Override
    public List<GooGoods> selectGooGoodsList(GooGoods gooGoods)
    {
        List<GooGoods> list = gooGoodsMapper.selectGooGoodsList(gooGoods);
        /*list.forEach(e ->{
            if(StringUtils.isNotBlank(e.getPartsClassifyId())){
                List<Integer> idList = new ArrayList<>();
                List<String> stringList = Arrays.asList(e.getPartsClassifyId().split(","));
                stringList.forEach(id -> idList.add(Integer.parseInt(id)));
                List<PlaPartsClassify> plaPartsClassifyList = plaPartsClassifyMapper.selectList(new LambdaQueryWrapper<PlaPartsClassify>().in(PlaPartsClassify::getPartsClassifyId, idList));
                e.setPartsClassifyName(plaPartsClassifyList.stream().map(PlaPartsClassify::getPartsClassifyName).collect(Collectors.joining(",")));

                //库存
                List<GooGoodsSku> skuList = goodsSkuMapper.selectList(new LambdaQueryWrapper<GooGoodsSku>().eq(GooGoodsSku::getGoodsId,e.getGoodsId()).eq(GooGoodsSku::getDelFlag,"0"));
                if(skuList.isEmpty()){
                    e.setStockNum(0L);
                }else{
                    long stockNum = skuList.stream().mapToLong(GooGoodsSku::getGoodsStock).sum();
                    e.setStockNum(stockNum);
                }
            }
        });*/
        return list;
    }
    private List<GooGoods> selectGooGoodsList2(GooGoods gooGoods) {
        List<GooGoods> list = gooGoodsMapper.selectGooGoodsList(gooGoods);
        return list;
    }

    /**
     * 新增商品
     *
     * @param goodsDTO 商品
     * @return 结果
     */
    @Override
    @Transactional
    public ApiResult insertGooGoods(GoodsAddDTO goodsDTO)
    {
        //如果是积分商品
        if(goodsDTO.getIsJf()==1){
            //1.插入goo_goods
            GooGoods goods = new GooGoods();
            BeanUtils.copyProperties(goodsDTO,goods);
            gooGoodsMapper.insert(goods);
        }else{
            CarPartsShop carPartsShop = carPartsShopMapper.selectOne(new LambdaQueryWrapper<CarPartsShop>().eq(CarPartsShop::getCarPartsShopId, goodsDTO.getCarPartsShopId()));
            if(carPartsShop == null){
                return ApiResult.error("汽配商编号错误或不存在");
            }
            //1.插入goo_goods
            GooGoods goods = new GooGoods();
            /*goods.setStoreId(carPartsShop.getStoreId());
            BeanUtils.copyProperties(goodsDTO,goods);


            gooGoodsMapper.insertGooGoods(goods);

            //4.商品规格  goo_goods_specs   goo_goods_specs_value
            insertGoodsSpecs(goodsDTO.getSpecsList(),goods.getGoodsId());

            //5.商品参数  goo_goods_parameter  goo_goods_parameter_value
            insertGoodsParameter(goodsDTO.getParameterList(),goods.getGoodsId());

            //6.商品sku  goo_goods_sku
            insertGoodsSku(goodsDTO.getSkuList(),goods.getGoodsId());*/
        }


        return ApiResult.success();
    }

    private void insertGoodsSku(List<GooGoodsSku> list, Long goodsId) {
        if(!list.isEmpty()){
            list.forEach(e -> {
                GooGoodsSku sku = new GooGoodsSku();
                sku.setGoodsId(goodsId);
                if(StringUtils.isNotEmpty(e.getSpecsIds())){
                    sku.setSpecsIds(e.getSpecsIds());
                }
                if(StringUtils.isNotEmpty(e.getSpecsNames())){
                    sku.setSpecsNames(e.getSpecsNames());
                }

                sku.setGoodsPrice(e.getGoodsPrice());
                sku.setGoodsStock(e.getGoodsStock());
                goodsSkuMapper.insert(sku);
            });
        }
    }

    public void insertGoodsParameter(List<GooGoodsParameter> list, Long goodsId){
        //商品修改时先删除相关数据 再新增
        goodsParameterMapper.delete(new LambdaQueryWrapper<GooGoodsParameter>().eq(GooGoodsParameter::getGoodsId,goodsId));
        goodsParameterValueMapper.delete(new LambdaQueryWrapper<GooGoodsParameterValue>().eq(GooGoodsParameterValue::getGoodsId,goodsId));
        if(!list.isEmpty()){
            list.forEach(parameter -> {
                GooGoodsParameter goodsParameter = new GooGoodsParameter();
                goodsParameter.setGoodsId(goodsId);
                goodsParameter.setGoodsParameterName(parameter.getGoodsParameterName());
                goodsParameterMapper.insert(goodsParameter);
                if(!parameter.getParameterValueList().isEmpty()){
                    parameter.getParameterValueList().forEach(parameterValue -> {
                        GooGoodsParameterValue goodsParameterValue = new GooGoodsParameterValue();
                        goodsParameterValue.setGoodsId(goodsId);
                        goodsParameterValue.setGoodsParameterId(goodsParameter.getGoodsParameterId());
                        goodsParameterValue.setGoodsParameterValue(parameterValue.getGoodsParameterValue());
                        goodsParameterValueMapper.insert(goodsParameterValue);
                    });
                }
            });
        }
    }

    public void insertGoodsSpecs(List<SpeSpecs> list, Long goodsId){
        //商品修改时 先删除相关数据 再新增
        goodsSpecsMapper.delete(new LambdaQueryWrapper<GooGoodsSpecs>().eq(GooGoodsSpecs::getGoodsId,goodsId));
        goodsSpecsValueMapper.delete(new LambdaQueryWrapper<GooGoodsSpecsValue>().eq(GooGoodsSpecsValue::getGoodsSpecsId,goodsId));
        if(!list.isEmpty()){
            list.forEach(specs -> {
                GooGoodsSpecs goodsSpecs = new GooGoodsSpecs();
                goodsSpecs.setGoodsId(goodsId);
                goodsSpecs.setSpecsId(specs.getSpecsId());
                goodsSpecsMapper.insert(goodsSpecs);
                if(!specs.getSpecsValueList().isEmpty()){
                    specs.getSpecsValueList().forEach(specsValue -> {
                        GooGoodsSpecsValue goodsSpecsValue = new GooGoodsSpecsValue();
                        goodsSpecsValue.setGoodsId(goodsId);
                        goodsSpecsValue.setGoodsSpecsId(goodsSpecs.getGoodsSpecsId());
                        goodsSpecsValue.setSpecsValueId(specsValue.getSpecsValueId());
                        goodsSpecsValueMapper.insert(goodsSpecsValue);
                    });
                }
            });
        }
    }



    /**
     * 修改商品
     *
     * @param goodsDTO 商品
     * @return 结果
     */
    @Transactional
    @Override
    public ApiResult updateGooGoods(GoodsEditDTO goodsDTO)
    {
        //1.修改商品主表
        GooGoods goods = gooGoodsMapper.selectById(goodsDTO.getGoodsId());
        if(goods == null){
            return ApiResult.error("商品编号错误或不存在");
        }

        BeanUtils.copyProperties(goodsDTO,goods);

        gooGoodsMapper.updateById(goods);
        if(goods.getIsJf()==0){

            //5.修改商品参数
            insertGoodsParameter(goodsDTO.getParameterList(),goods.getGoodsId());

            //6.修改商品sku
            updateGoodsSku(goodsDTO.getSkuList());
        }
        return ApiResult.success();
    }

    public void updateGoodsSku(List<GooGoodsSku> list) {
        list.forEach(e -> {
            GooGoodsSku sku = goodsSkuMapper.selectById(e.getGoodsSkuId());
            if (null != sku){
                sku.setGoodsPrice(e.getGoodsPrice());
                sku.setGoodsStock(e.getGoodsStock());
                goodsSkuMapper.updateById(sku);
            }
        });
    }

    /**
     * 批量删除商品
     *
     * @param goodsIds 需要删除的商品主键
     * @return 结果
     */
    @Override
    public int deleteGooGoodsByGoodsIds(Long[] goodsIds)
    {
        return gooGoodsMapper.deleteGooGoodsByGoodsIds(goodsIds);
    }

    /**
     * 删除商品信息
     *
     * @param goodsId 商品主键
     * @return 结果
     */
    @Override
    public int deleteGooGoodsByGoodsId(Long goodsId)
    {
        return gooGoodsMapper.deleteGooGoodsByGoodsId(goodsId);
    }

    /**
     * 商品上下架
     * @param goodsId
     * @param publishStatus
     * @return
     */
    @Override
    public ApiResult updatePublishStatus(Long goodsId, String publishStatus) {
        GooGoods goods = gooGoodsMapper.selectById(goodsId);
        /*goods.setPublishStatus(publishStatus);*/
        gooGoodsMapper.updateById(goods);
        return ApiResult.success();
    }

    /**
     * 商品app首页推荐
     * @param goodsId
     * @param appIndexStatus
     * @return
     */
    @Override
    public ApiResult updateAppIndexStatus(Long goodsId, String appIndexStatus) {
        GooGoods goods = gooGoodsMapper.selectById(goodsId);
        goods.setAppIndexStatus(appIndexStatus);
        gooGoodsMapper.updateById(goods);
        return ApiResult.success();
    }

    /**
     * 商品app店铺首页推荐
     * @param goodsId
     * @param storeIndexStatus
     * @return
     */
    @Override
    public ApiResult updateStoreIndexStatus(Long goodsId, String storeIndexStatus) {
        GooGoods goods = gooGoodsMapper.selectById(goodsId);
        /*goods.setStoreIndexStatus(storeIndexStatus);*/
        gooGoodsMapper.updateById(goods);
        return ApiResult.success();
    }

    @Override
    @Transactional
    public ApiResult updateViolationStatus(Long goodsId, String violationStatus, String remark) {
        GooGoods goods = gooGoodsMapper.selectById(goodsId);
        goods.setRemark(remark);
        goods.setMarketEnable(violationStatus);
        if(violationStatus.equals("0")){
            goods.setRemark("");
            gooGoodsMapper.updateById(goods);
        }else{
           /* String content = "您的商品《"+goods.getGoodsName()+"》因《"+remark+"》被平台下架了,请注意查看。";

            goods.setRemark(remark);


            // 消息通知新增
            CarPartsShop carPartsShop = carPartsShopMapper.selectById(goods.getCarPartsShopId());
            if(carPartsShop==null){
                throw new ServiceException("商家不存在");
            }

            UserNotice userNotice = new UserNotice();
            userNotice.setSide(1);
            userNotice.setContent(content);
            userNotice.setUserId(carPartsShop.getUserId());
            userNotice.setChildType(23);
            userNotice.setSourceId(goodsId);
            userNotice.setNoticeType(1);

            CarPartsShopAudit carPartsShopAudit = carPartsShopAuditMapper.selectById(carPartsShop.getCarPartsShopAuditId());
            //生成验证码


            //用腾讯云短信给手机号发送验证码
            String resStr = SMSUtil.sendSMS(carPartsShopAudit.getContactPhone(), goods.getGoodsName(),remark);
            if(!resStr.equals("success")){
                return ApiResult.error("发送短信失败！");
            }
            goods.setPublishStatus("0");*/
            gooGoodsMapper.updateById(goods);
        }
        return ApiResult.success();
    }

    @Override
    public List<GooGoods> selectGooGoodsIntegralList(GoodsIntegralListDTO gooGoods) {
        List<GooGoods> list = gooGoodsMapper.selectGooGoodsIntegralList(gooGoods);
        return list;
    }

    @Override
    public HelpDocument getIntegralRule() {
        return helpDocumentMapper.selectOne(new LambdaQueryWrapper<HelpDocument>()
                .eq(HelpDocument::getDistinguish,3));
    }

    @Override
    public int editIntegralRule(HelpDocument helpDocument) {
        HelpDocument helpDocument1 = helpDocumentMapper.selectOne(new LambdaQueryWrapper<HelpDocument>().eq(HelpDocument::getDistinguish, 3));
        if (helpDocument1==null){
            helpDocumentMapper.insert(helpDocument);
        }else {
            helpDocument1.setDocContent(helpDocument.getDocContent());
            helpDocumentMapper.updateById(helpDocument1);
        }
        return 1;
    }

    @Override
    public int editIntegralDraw(IntegralDrawDTO integralDrawDTO) {
        List<IntegralDrawDetailDTO> drawList = integralDrawDTO.getParameterList();
        if(CollectionUtil.isNotEmpty(drawList)){
            jfDrawService.remove(new LambdaQueryWrapper<JfDraw>().eq(JfDraw::getDelFlag,0));
        }
        for(IntegralDrawDetailDTO drawDetailDTO : drawList){
            JfDraw draw = new JfDraw();
            draw.setDrawPercent(drawDetailDTO.getDrawPercent());
            draw.setDrawNum(drawDetailDTO.getDrawNum());
            jfDrawService.insertJfDraw(draw);
        }
        return 1;
    }

    @Override
    public List<JfDraw> getIntegralDraw() {
        return jfDrawMapper.selectList(new LambdaQueryWrapper<JfDraw>()
                .eq(JfDraw::getDelFlag,0));
    }

    @Override
    public HelpDocument getIntegralDrawRule() {
        return helpDocumentMapper.selectOne(new LambdaQueryWrapper<HelpDocument>()
                .eq(HelpDocument::getDistinguish,6));
    }

    @Override
    public int editIntegralDrawRule(HelpDocument helpDocument) {
        HelpDocument helpDocument1 = helpDocumentMapper.selectOne(new LambdaQueryWrapper<HelpDocument>().eq(HelpDocument::getDistinguish, 6));
        if (helpDocument1==null){
            helpDocumentMapper.insert(helpDocument);
        }else {
            helpDocument1.setDocContent(helpDocument.getDocContent());
            helpDocumentMapper.updateById(helpDocument1);
        }
        return 1;
    }


}
